package com.qudian.pay.redis;

import java.util.concurrent.TimeUnit;
import com.qudian.pay.redis.exception.RedisException;
import com.qudian.pay.redis.support.IAtomic;
import redis.clients.jedis.ShardedJedis;

public class RedisAtomicManager extends RedisManager implements IAtomic<String> {
	
	@Override
	public void set(String key, long value) {
		ShardedJedis jedis = this.getPool().getResource();
		try {
			jedis.set(key, String.valueOf(value));
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public void set(String key, long value, long timeout, TimeUnit unit) {
		ShardedJedis resource = this.getPool().getResource();
		try {
			resource.setex(key, (int) unit.toSeconds(timeout), String.valueOf(value));
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			resource.close();
		}
	}
	
	@Override
	public Long incrementAndGet(String key, long delta) {
		ShardedJedis jedis = this.getPool().getResource();
		try {
			return jedis.incrBy(key, delta);
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public Long decrementAndGet(String key, long delta) {
		ShardedJedis jedis = this.getPool().getResource();
		try {
			return jedis.incrBy(key, -delta);
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
	
	@Override
	public Long getLong(String key) {
		ShardedJedis jedis = this.getPool().getResource();
		try {
			if (isExist(key))
				return jedis.incrBy(key, 0);
			else
				return null;
		} catch (Exception e) {
			throw new RedisException(-1, e.getMessage(), e);
		} finally {
			jedis.close();
		}
	}
}
